/**  
* <p>Title: SpringGlobalExceptionHandler.java</p>  
* <p>Description: </p>  
* <p>Copyright: Copyright (c) 2017</p>  
* <p>Company: http://www.richfit.com/</p>  
* @author Administrator
* @date 2020年1月13日  
* @version 1.0  
*/  
package com.rf.richfitwheel.admin.conf;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.common.utils.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**  
 * 全局异常处理类
* <p>Title: SpringGlobalExceptionHandler</p>  
* <p>Description: </p>  
* @author Administrator  
* @date 2020年1月13日  
*/
public class SpringGlobalExceptionHandler extends SimpleMappingExceptionResolver {
	
	private static final Logger log = LoggerFactory.getLogger(SpringGlobalExceptionHandler.class);
	
	public static final String UTF_8 = "utf-8";
    public static final String ACCEPT = "Accept";
    public static final String APPLICATION_JSON = "application/json";
    public static final String X_REQUESTED_WITH = "X-Requested-With";
    public static final String XML_HTTP_REQUEST = "XMLHttpRequest";
    public static final String APPLICATION_JSON_CHARSET_UTF_8 = "application/json; charset=utf-8";
	
	public static final String CONTENT_TYPE = "Content-Type";
	/* （非 Javadoc）
	 * <p>Title: doResolveException</p>  
	 * <p>Description: </p>  
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @return  
	 * @see org.springframework.web.servlet.handler.SimpleMappingExceptionResolver#doResolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)  
	 */
	@Override
	protected ModelAndView doResolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
			Exception ex) {
		 ModelAndView modelAndView;
	        httpServletResponse.setCharacterEncoding(UTF_8);
	        String viewName = determineViewName(ex,httpServletRequest);
	        String accept = StringUtils.isBlank(httpServletRequest.getHeader(ACCEPT)) ? httpServletRequest.getHeader(CONTENT_TYPE) : httpServletRequest.getHeader(ACCEPT);
	        boolean isJsonXMLRequest = accept != null && (accept.indexOf(APPLICATION_JSON) != -1
	            || (httpServletRequest.getHeader(X_REQUESTED_WITH) != null
	            && httpServletRequest.getHeader(X_REQUESTED_WITH).indexOf(XML_HTTP_REQUEST) != -1));
	        if (!isJsonXMLRequest) {
				log.error("服务器出错", ex);
	            //非 json xml ajax 请求 返回正常的视图
	            Integer statusCode = determineStatusCode(httpServletRequest, viewName);
	            if (statusCode != null) {
	                applyStatusCodeIfPossible(httpServletRequest, httpServletResponse, statusCode);
	             }
	            modelAndView = getModelAndView(viewName, ex, httpServletRequest);
	        } else {
	        	modelAndView = new ModelAndView();
	        	httpServletResponse.setContentType(APPLICATION_JSON_CHARSET_UTF_8);
                FastJsonJsonView view = new FastJsonJsonView();
                if (ex instanceof UnauthorizedException) {
                	R r = R.error(HttpStatus.FORBIDDEN.value(), "由于权限不足请求被拒绝!");//没权限直接返回403,不同于401这个代表的是资源没有权限而不是没登录
                	view.setAttributesMap(r);
                } else {
                	log.error("服务器出错", ex);
                	R r = R.error(998, ex.getMessage() == null ? "服务器出错，请联系管理员!" : ex.getMessage());
                	view.setAttributesMap(r);
                }
                modelAndView.setView(view);
	            /*PrintWriter writer = null;
	            try {
	                //json xml 请求 ajax请求 返回json格式的错误信息
	                // json 请求返回
	                httpServletResponse.setContentType(APPLICATION_JSON_CHARSET_UTF_8);
	                FastJsonJsonView view = new FastJsonJsonView();
	                if (ex instanceof UnauthorizedException) {
	                	R r = R.error(HttpStatus.SC_FORBIDDEN, "由于权限不足请求被拒绝");//没权限直接返回403,不同于401这个代表的是资源没有权限而不是没登录
	                	view.setAttributesMap(r);
	                } else {
	                	R r = R.error(998, ex.getMessage());
	                	view.setAttributesMap(r);
	                }
	                modelAndView.setView(view);
	                writer = httpServletResponse.getWriter();
	                
	                writer.write(JsonUtils.mapToJson(r));
	                writer.flush();
	            } catch (IOException e) {
	                if (log.isInfoEnabled()) {
	                    logger.error("SpringGlobalExceptionHandler exception  ",e);
	                }
	            }finally{
	                if(null != writer){
	                    writer.flush();
	                    writer.close();
	                }
	            }
	            return null;*/
	        }
	        return modelAndView;
	}
    
    
}
